import java.util.Arrays;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: Zguoxu
 * Date: 2025-03-02
 * Time: 8:41
 */
public class Test {
    public static void bubbleSort(int[] array) {
        //冒泡排序
        for (int i = 0; i < array.length - 1; i++) {
            //一共有 i 趟排序
            boolean flag = false;
            for (int j = 0; j < array.length - 1 - i; j++) {
                //每趟排序走 j 步
                if(array[j] > array[j + 1]) {
                    int tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                    flag = true;
                }
            }
            if(flag == false) {
                break;
            }
        }
    }

    public static int binarySearch(int[] array, int key) {
        int left = 0;
        int right = array.length - 1;
        while(left <= right) {
            int mid = (right - left) / 2 + left;
            if(array[mid] < key) {
                left = mid + 1;
            }else if(array[mid] > key) {
                right = mid - 1;
            }else if(array[mid] == key) {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] array1 = {1, 12, 3, 56, 0, 2};
        Arrays.sort(array1);//将数组从小到大排序
        System.out.println(Arrays.toString(array1));
        System.out.println(Arrays.binarySearch(array1, 13));//自带二分查找
        System.out.println(binarySearch(array1, 56));//自己实现二分查找

        int[] array2 = {0, 1, 2, 3, 12, 56};
        boolean flag = Arrays.equals(array1, array2);//比较两个数组对应元素是否相等
        System.out.println(flag);// true

        int[] array3 = new int[5];
        Arrays.fill(array3, -1);//将 array3 数组中所有元素填充成 -1
        Arrays.fill(array3,1,3,2);//将下标 1 到下标 3 不包括下标 3 的元素填充 2
        System.out.println(Arrays.toString(array3));
    }

    public static double average(int[] array) {
        int sum = 0;
        for (int x: array) {
            sum += x;
        }
        return ((double)sum / array.length);
    }

    public static void main2(String[] args) {
        //求数组元素平均值
        int[] array = {1, 2, 3, 4, 5};
        System.out.println(average(array));
    }

    public static void main1(String[] args) {
        int[] array = new int[]{1, 2, 3, 4, 5};
        int[] copy = Arrays.copyOf(array, array.length);//数组拷贝,可以同过增减第二个参数来调整 copy 数组的大小
        System.out.println(Arrays.toString(copy));//数组转字符串

        int[] copy2 = Arrays.copyOfRange(array,1,3);//[1, 3)从下标 1 拷贝到下标 3，不包括 3 下标
        System.out.println(Arrays.toString(copy2));


        System.out.println(Arrays.toString(array));//数组转字符串，直接输出字符串
    }
}
